import { DELETE_TOKEN, GET_TOKEN, SET_TOKEN } from "@/utils/token";
import { defineStore } from "pinia";
import { reactive, ref } from "vue";
import type { UserType } from "@/api/management/user/types";
import { anyRoute, asyncRoute, constantRoute } from "@/router/routes";
import router from "@/router";
import cloneDeep from "lodash/cloneDeep";
import { userInfo } from "@/api/management/user";

export const useUserStore = defineStore("user", () => {
  // 用户 token
  let token = ref(GET_TOKEN());
  // 用户菜单
  let menuList = ref(constantRoute);

  let user = reactive<UserType>({
    nickname: "",
    avatar: "",
    buttons: [],
    routes: [],
  });

  function setUserToken(value: string) {
    token.value = value;
    SET_TOKEN(value);
  }

  async function setUser() {
    const data = await userInfo();
    if (data.code === 200) {
      user.avatar = data.data.avatar;
      user.nickname = data.data.nickname;
      user.buttons = data.data.buttons;
      user.routes = data.data.routes;

      const userRoute = filterAsyncRoute(
        cloneDeep(asyncRoute),
        data.data.routes
      );
      [...userRoute, anyRoute].forEach((item) => router.addRoute(item));
      menuList.value = [...constantRoute, ...userRoute, anyRoute];
    } else {
      return Promise.reject(new Error(data.message));
    }
  }

  async function deleteUser() {
    user.avatar = "";
    user.nickname = "";
    user.buttons = [];
    user.routes = [];

    token.value = "";
    menuList.value = [];
    DELETE_TOKEN();
  }

  // asyncRoute 异步路由 用户拥有的路由名称
  function filterAsyncRoute(asyncRoute: any, userHaveRoutes: any) {
    return asyncRoute.filter((item: any) => {
      if (userHaveRoutes.includes(item.name)) {
        if (item.children && item.children.length > 0) {
          item.children = filterAsyncRoute(item.children, userHaveRoutes);
        }
        return true;
      }
    });
  }

  return { user, token, menuList, setUserToken, setUser, deleteUser };
});
